package com.jt.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Configuration
@EnableResourceServer//是资源服务，就要写这个注解
@EnableGlobalMethodSecurity(prePostEnabled = true)//在方法的层面去进行权限控制
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    //令牌解析器
    @Autowired
    private TokenStore tokenStore;

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        //通过tokenStore获取token解析器对象，基于此对象对token进行解析
        resources.tokenStore(tokenStore);

    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        //1.关闭跨域攻击
        http.csrf().disable();
        //此代码表示：不是所有用户都能上传文件，限制用户上传的权限
        http.exceptionHandling()
                .accessDeniedHandler(accessDeniedHandler());
        //2.放行相关请求（只写此代码是放行了全部）
        http.authorizeRequests()
                //.antMatchers("/resource/upload/**").authenticated() //添加这个条件，限制此资源的放行。
                .anyRequest().permitAll();
    }


    public AccessDeniedHandler accessDeniedHandler() {
        return (request,response,e)->{
            Map<String,Object> map = new HashMap<>();
            map.put("state", HttpServletResponse.SC_FORBIDDEN);
            map.put("message", "没有访问权限，请联系管理员");
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json;charset=utf-8");
            PrintWriter out = response.getWriter();
            String result = new ObjectMapper().writeValueAsString(map);
            out.println(result);
            out.flush();
        };

    }
}
